package org.ef.anticheck;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;

/**
 * 查询 Activity
 * 
 * @author zenglu.liu
 */
public class QueryFromInput extends Activity implements OnClickListener {

	private Query compositeQuery;

	private static final String TABLE_NAME = "siberian_blacklist";

	// TODO change url
	private static final String URL_PATTERN = "http://173.224.215.10/query?t=1&n={phone}";

	@Override
	public void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		this.setContentView(R.layout.query_from_input);

		final Query localQuery = new LocalQuery(
				new DBMgmt(this).getReadableDatabase(), TABLE_NAME);
		final Query remoteQuery = new RemoteQuery(URL_PATTERN);

		this.compositeQuery = new CompositeQuery(localQuery, remoteQuery);

		this.findViewById(R.id.query_submit_button).setOnClickListener(this);
	}

	public void onClick(final View v) {
		switch (v.getId()) {
		case R.id.query_submit_button:
			final EditText text =
			(EditText) this.findViewById(R.id.phone_number_edittext);

			Recoder r = null;
			try {
				r = this.compositeQuery.execute(text.getText().toString());
			} catch (final QueryException e) {
				r = null;
			}

			if (r == null) {
				((TextView) this.findViewById(R.id.query_result_label))
				.setText(R.string.empty_query_result);
			} else {
				((TextView) this.findViewById(R.id.query_result_label))
				.setText(r.toString());
			}
			break;
		}
	}
}
